#include "writer.h"
#include <QDebug>
#include <QtTest/QTest>

Writer::Writer(QString name, int writeTime, int editTime, Shelf *shelf, QObject *parent) :
    name(name), writeTime(writeTime), editTime(editTime), shelf(shelf), isActive(false), QObject(parent)
{
    connect(this, SIGNAL(activeChange(bool)), this, SLOT(activeChanged(bool)));
}

void Writer::activeChanged(bool active){
    if(isActive != active){
        isActive = active;
        if(isActive) emit actived();
        else emit waited();
    }
}

void Writer::run(){
    int active;
    int high = 1;
    int low = 0;
    while(true){
        active = qrand() % ((high + 1) - low) + low;
        switch(active){
            case 0: //write
                emit activeChange(true);
                QTest::qSleep(writeTime*1000);
                while(!shelf->tryPutNewBook(name)){
                    emit activeChange(false);
                }
                emit newBookWrited();
                break;
            case 1: //edit
                int index;
                while(!shelf->tryTakeBookForEdit(name, index)){
                    emit activeChange(false);
                }
                emit activeChange(true);
                QTest::qSleep(editTime*1000);
                shelf->tryPutBook(index);
                break;
        }

    }
}

